package com.shengwei.truck.driver.model;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.MutableLiveData;
import com.shengwei.truck.driver.bean.Result;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.adapter.rxjava.HttpException;
import rx.Subscription;


/**
 * 访问首页接口：调用服务器接口获取列表数据
 */
public class BaseDataSource<T> implements LifecycleObserver {
    private  String TAG = BaseDataSource.class.getSimpleName() ;
    protected Subscription mSubscription;
    protected static final String HTTP_EXCEPTION = "http";
    /**
     * 使用LifeCycle自动调用：即当Activity进入OnStop生命周期时，会被LifecycleObserver感知到
     * 从而自动调用unSubscription函数来释放资源
     */
/*    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void unSubscription()
    {
        if(mSubscription != null) {
            mSubscription.unsubscribe();
            Log.i(TAG,"AACunSubscription");
        }
    }*/

    /**
     * 当throwable里的erroBody Json串里包含code时，说明是业务异常，
     * 直接返回接口中的message; 否则是HTTP异常
     * @param throwable
     * @return 异常错误消息
     */
    public String getExceptionContent(Throwable throwable)
    {
        HttpException httpException = (HttpException) throwable;
        ResponseBody responseBody = httpException.response().errorBody();

        if (responseBody != null) {
            try {
               String erroBodyContent = responseBody.string();
               JSONObject jsonErrorBody = new JSONObject(erroBodyContent);
               boolean isContainCode = erroBodyContent.contains("code");
               //如果服务器返回了JSON且有code字段时，证明是业务异常
               if(isContainCode) {
                   String message = jsonErrorBody.getString("message");
                   return message;
               }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
        return HTTP_EXCEPTION;
    }


    /**
     * 处理
     * @param throwable
     * @param liveData
     * @return
     */
    public String dealExceptionContent(Throwable throwable, MutableLiveData<Result<T>> liveData)
    {
        HttpException httpException = (HttpException) throwable;
        ResponseBody responseBody = httpException.response().errorBody();

        if (responseBody != null) {
            try {
                String erroBodyContent = responseBody.string();
                JSONObject jsonErrorBody = new JSONObject(erroBodyContent);
                boolean isContainCode = erroBodyContent.contains("code");
                //业务异常：  如果服务器返回了JSON且有code字段时，证明是业务异常
                if(isContainCode) {
                    String message = jsonErrorBody.getString("message");
                    int code = jsonErrorBody.getInt("code");
                    liveData.postValue(Result.failure(code+";"+message));
                    return message;
                }
                else {  //HTTP异常
                    liveData.postValue(Result.error(throwable));
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }

        return HTTP_EXCEPTION;
    }



}